package com.facebook_graph;

import java.util.ArrayList;
import java.util.List;

import cn.org.cute.ebocy.util.NormalUtil;
import cn.org.cute.security.domain.PlatformUser;

import com.facebook_graph.restapi.Connection;
import com.facebook_graph.restapi.DefaultFacebookClient;
import com.facebook_graph.restapi.DefaultLegacyFacebookClient;
import com.facebook_graph.restapi.FacebookClient;
import com.facebook_graph.restapi.FacebookException;
import com.facebook_graph.restapi.FacebookJsonMappingException;
import com.facebook_graph.restapi.Parameter;
import com.facebook_graph.restapi.json.JsonException;
import com.facebook_graph.restapi.json.JsonObject;
import com.facebook_graph.restapi.types.User;

public class FacebookGraphRestClient {
	 private static final String FACEBOOK_GRAPH_ENDPOINT_URL = "https://graph.facebook.com";
	 private static final String FACEBOOK_LEGACY_ENDPOINT_URL = "https://api.facebook.com/method";
	DefaultLegacyFacebookClient restClient;
	private FacebookClient graphFacebookClient;
	private static String fields = "name,gender,locale,picture";
	public static Parameter parameter = Parameter.with("fields", fields);
	public static Parameter idparameter = Parameter.with("fields", "id");
	private String accessToken = null;

	public FacebookGraphRestClient(String accessToken) {
		graphFacebookClient = new DefaultFacebookClient(accessToken);
		restClient = new DefaultLegacyFacebookClient(accessToken);
		this.accessToken = accessToken;
	}

	/**
	 * 获得多个用户信息，必须是自己的好友 { "1355346801": { "name": "Sean Xiao", "gender":
	 * "female", "locale": "zh_CN", "id": "1355346801", "picture":"http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs324.snc4/41427_1355346801_3398_q.jpg"
	 * }, "100001610288893": { "name":"\u0e20\u0e34\u0e18\u0e32\u0e23\u0e32\u0e27\u0e14\u0e35 \u0e40\u0e08\u0e23\u0e34\u0e0d\u0e1e\u0e31\u0e19\u0e18\u0e4c"
	 * , "gender": "female", "locale": "th_TH", "id": "100001610288893",
	 * "picture":"http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs717.ash1/161428_100001610288893_6526179_q.jpg"
	 * } }
	 * 
	 * @return
	 * @throws FacebookException
	 * @throws FacebookJsonMappingException
	 */
	public JsonObject users_getInfos(List<String> ids) {
		JsonObject usersObject = null;
		if (ids != null && ids.size() > 0) {
			usersObject = graphFacebookClient.fetchObjects(ids, parameter);
		}
		return usersObject;
	}

	/**
	 * 获得多个用户信息
	 * 
	 * @param ids
	 * @return
	 */
	public List<PlatformUser> getUserInfos(List<String> ids) {
		List<PlatformUser> xnUserList = null;
		JsonObject usersObject = users_getInfos(ids);
		if (usersObject == null) {
			return xnUserList;
		}

		xnUserList = new ArrayList();
		for (String id : ids) {
			JsonObject userObject = null;
			try {
				userObject = usersObject.getJsonObject(id);
				PlatformUser xnUser = this.getXnUserfromJsonObject(userObject);
				if (xnUser != null && xnUser.getPfId() != null
						&& !"".equals(xnUser.getPfId())
						&& id.equals(xnUser.getPfId())) {
					xnUserList.add(xnUser);
				}
			} catch (JsonException e) {
				// e.printStackTrace();
			}
		}

		return xnUserList;

	}

	/**
	 * JsonObject 对象转化为XnUser 对象
	 * 
	 * @param usersObject
	 * @return
	 */
	public PlatformUser getXnUserfromJsonObject(JsonObject userObject) {
		PlatformUser xnUser = null;
		if (userObject == null) {
			return xnUser;
		}

		try {
			xnUser = new PlatformUser();
			xnUser.setPfId(userObject.getString("id"));
			xnUser.setPfName(userObject.getString("name"));

			// sex
			String gender = "0";
			if (userObject.has("gender")) {
				gender = userObject.getString("gender");
				if (gender != null
						&& !"".equals(gender)
						&& (gender.equalsIgnoreCase("male")
								|| gender.indexOf("男") >= 0 || "мужской"
								.equalsIgnoreCase(gender))) {
					gender = "1";
				} else {
					gender = "0";
				}
			}
			xnUser.setPfSex(gender);

			// pic
			String pic = null;
			if (userObject.has("picture")) {
				pic = userObject.getString("picture");
			}
			if (pic == null || "".equalsIgnoreCase(pic)
					|| "null".equalsIgnoreCase(pic)
					|| "undefined".equalsIgnoreCase(pic)) {
				pic = "http://static.ak.fbcdn.net/pics/d_silhouette.gif";
			}

			xnUser.setPfHeadurl(pic);
			xnUser.setPfMainurl(pic);
			xnUser.setPfTinyurl(pic);

			// birthday
			if (userObject.has("birthday")) {
				String birthday = userObject.getString("birthday");
				if (birthday != null && !"".equalsIgnoreCase(birthday)
						&& !"null".equalsIgnoreCase(birthday)
						&& !"undefined".equalsIgnoreCase(birthday)) {
					//xnUser.setPfBday(birthday);
				}
			}

			// locale
			if (userObject.has("locale")) {
				String locale = userObject.getString("locale");
				if (locale != null && !"".equals(locale)
						&& !"null".equalsIgnoreCase(locale)
						&& !"undefined".equalsIgnoreCase(locale)) {
					//xnUser.setPfCity(locale);
				}
			}
		} catch (JsonException e) {
			// e.printStackTrace();
			return null;
		}
		return xnUser;

	}

	/**
	 * user 对象转化为XnUser 对象
	 * 
	 * @param usersObject
	 * @return
	 */
	public PlatformUser getXnUserfromUser(User user) {
		PlatformUser xnUser = null;
		if (user == null) {
			return xnUser;
		}

		xnUser = new PlatformUser();
		xnUser.setPfId(user.getId());
		xnUser.setPfName(user.getName());

		// sex
		String gender = user.getGender();
		if (gender != null) {
			if (!"".equals(gender)
					&& (gender.equalsIgnoreCase("male")
							|| gender.indexOf("男") >= 0 || "мужской"
							.equalsIgnoreCase(gender))) {
				gender = "1";
			} else {
				gender = "0";
			}
		}
		xnUser.setPfSex(gender);

		// pic
		String picture = user.getPicture();
		if (picture == null || "".equalsIgnoreCase(picture)
				|| "null".equalsIgnoreCase(picture)
				|| "undefined".equalsIgnoreCase(picture)) {
			picture = "http://static.ak.fbcdn.net/pics/d_silhouette.gif";
		}

		xnUser.setPfHeadurl(picture);
		xnUser.setPfMainurl(picture);
		xnUser.setPfTinyurl(picture);

		// birthday
		String birthday = user.getBirthday();
		if (birthday != null && !"".equalsIgnoreCase(birthday)
				&& !"null".equalsIgnoreCase(birthday)
				&& !"undefined".equalsIgnoreCase(birthday)) {
			//xnUser.setPfBday(birthday);
		}

		// locale
		String locale = user.getLocale();
		if (locale != null && !"".equals(locale)
				&& !"null".equalsIgnoreCase(locale)
				&& !"undefined".equalsIgnoreCase(locale)) {
			//xnUser.setPfCity(locale);
		}

		return xnUser;

	}

	/**
	 * 获得用户信息 users.getInfo
	 * 
	 * @return
	 * @throws FacebookException
	 */
	public User user_Profile(String pfId) {
		User user = null;
		if(NormalUtil.isNull(pfId)){
			user = graphFacebookClient.fetchObject("me", User.class,parameter); 
		}else{
			user = graphFacebookClient.fetchObject(pfId, User.class,parameter);
		}
		//System.err.println("user--------->" + user);
		return user;
	}

	/**
	 * 获得当前登录用户的信息
	 * 
	 * @return
	 */
	public PlatformUser getUser_Profile(String pfId) {
		User user = this.user_Profile(pfId);
		PlatformUser xnUser = this.getXnUserfromUser(user);
		return xnUser;
	}

	/**
	 * 获得当前登录用户/或好友 的所有好友信息 ifProperties 是否要获得用户的属性
	 * 
	 * @return
	 */
	public Connection<User> user_ProfileFriends(String uid, boolean ifProperties) {
		JsonObject friendsObject = null;
		Connection<User> myFriends = null;
		String method = "me/friends";
		if (uid != null && !"".equals(uid)) {
			method = uid + "/friends";
		}
		if (ifProperties) {
			myFriends = graphFacebookClient.fetchConnection(method, User.class,
					parameter);
		} else {
			myFriends = graphFacebookClient.fetchConnection(method, User.class,
					idparameter);
		}
		return myFriends;
	}

	/**
	 * 获得加入app的好友id
	 * 
	 * @return
	 */
	public List<String> getAppFriendIds(String uid) {
		List<String> appFriendIds = null;
		Connection<User> userIds = user_ProfileFriends(uid, false);
		if (userIds == null) {
			return appFriendIds;
		}

		List<User> userList = userIds.getData();
		if (userList != null && userList.size() > 0) {
			appFriendIds = new ArrayList();
			for (User user : userList) {
				appFriendIds.add(user.getId());
			}
		}

		return appFriendIds;
	}

	/**
	 * 获得加入app的好友详细信息
	 * 
	 * @return
	 */
	public List<PlatformUser> getAppFriendInfo(String uid) {
		List<PlatformUser> appFriendInfo = null;
		Connection<User> userIds = user_ProfileFriends(uid, true);
		if (userIds == null) {
			return appFriendInfo;
		}

		List<User> userList = userIds.getData();
		if (userList != null && userList.size() > 0) {
			appFriendInfo = new ArrayList();
			for (User user : userList) {
				PlatformUser xnUser = this.getXnUserfromUser(user);
				if (xnUser != null && xnUser.getPfId() != null
						&& !"".equals(xnUser.getPfId())) {
					appFriendInfo.add(xnUser);
				}

			}
		}

		return appFriendInfo;
	}

	/**
	 * 获得当前登录用户的加入应用的好友ID
	 * 
	 * @return
	 */
	public List<String> user_appFriends() {
		JsonObject friendsObject = null;
		List<String> appUserList = restClient.executeForList(
				"friends.getAppUsers", String.class);
		//System.err.println("user_appFriends--------->" + appUserList.toString());
		return appUserList;
	}
	
	/**
	 * 判断用户是否是粉丝
	 * 
	 * @return
	 */
	public boolean isPageFan(String uid,String page_id) {
	  if(NormalUtil.isNull(page_id)){
		  return false;
	  }
	  
	  String method = "/me/likes/"+page_id;
	  if(!NormalUtil.isNull(uid)){
		  method = "/"+uid+"/likes/"+page_id;
	  }
	  
	   String connectUrl = FACEBOOK_GRAPH_ENDPOINT_URL + method +"?access_token="+this.accessToken;	 
		String isfanObj  = NormalUtil.getURLConnectionInfo(connectUrl);
		//System.err.println(isfanObj);
		if(isfanObj != null && isfanObj.indexOf(page_id) > 0 ){
			return true;
		}
	

		return false;
	}

	/**
	 * 获得当前登录用户uid
	 * 
	 * @return
	 */
	public String users_getLoggedInUser() {
		String loggedInUser = restClient.execute("users.getLoggedInUser",
				String.class);
		//System.err.println("loggedInUser--------->" + loggedInUser);
		return loggedInUser;
	}
	
	
	/**
	 * 邮件发送
	 * @param uids 用户平台id用","隔开
	 * @param title 邮件标题
	 * @param body 邮件内容
	 * @return
	 */
	public String[] sendEmail(String uids, String title, String body) {
		String callBack = null;
		try {
			callBack=restClient.execute("notifications.sendEmail",
					String.class, Parameter.with("format", "json"), Parameter.with(
							"recipients", uids), Parameter.with("subject",
							title), Parameter.with("fbml", body));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return callBack.split(",");
	}
	
	

	public static void main(String[] arg) {
		String secret = "44058903f526d946c0f050c0081eb467";
		String requestCode = "Weu3lLWz4KXxF-mt8fZ4x1QQq3QsT6ijNzNTVzhdusU.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzMzg0NTg0MDAsImlzc3VlZF9hdCI6MTMzODQ1MTc1MSwib2F1dGhfdG9rZW4iOiJBQUFFV1hoVVA3WDRCQUYxa1NLd1pBZzVzTGhFd0ROVmNhS2V1VGdBZWhhZENjNmZYcFNmU3pzZUQzQjdXZ2RNRmpPM3RnOU82WkEwSFhFWkFaQ0VrRmpPNHlhbmhVUVN1aUFzYzl3OVpBblJXT0huRHNJdzM2IiwidXNlciI6eyJjb3VudHJ5IjoidHciLCJsb2NhbGUiOiJ6aF9DTiIsImFnZSI6eyJtaW4iOjIxfX0sInVzZXJfaWQiOiIxMzU1MzQ2ODAxIn0";
		java.util.Map returnMap = null;
		try {
			returnMap = FbDecoderUtil.parse_signed_request(requestCode, secret);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String accessToken = FbDecoderUtil.getAccessToken(returnMap);
		System.err.println("accessToken------->" + accessToken);
		FacebookGraphRestClient client = new FacebookGraphRestClient(
				accessToken);
		// System.err.println("client.users_getLoggedInUser()------->"+client.users_getLoggedInUser());
		//System.err.println("client.getAppFriendInfo()------->"+ client.user_appFriends());
		//String uids = "100001831833088";
		String uids = "100000552324368";
		String title="好友买卖中......";
		String body="<a href=\"http://apps.facebook.com/icutefriends\">给你的游戏......</a> <img src=\"http://profile.ak.fbcdn.net/hprofile-ak-snc4/173179_100001750634262_152663194_q.jpg\"/>";
		client.sendEmail(uids, title, body);
		
		//notifications.sendEmail Permissions
		// System.err.println("uers_getInfo)------->"+client.uers_getInfo());
		// System.err.println("users_getInfos)------->"+client.users_getInfos());
		// System.err.println("user_ProfileFriends)------->"+client.user_ProfileFriends(false));
		// System.err.println("user_appFriends)------->"+client.getAppFriendIds("100001134270802"));

	}

}

// Map paramsMap =
// FbDecoderUtil.parse_signed_request(signed_request,CuteConstants.SECRET_KEY);
// String token = FbDecoderUtil.getAccessToken(paramsMap);
// String pfId = FbDecoderUtil.getUserId(paramsMap);